<?php
/**
 * $Id$
 */

/**
 * 验证类
 *
 * @package Validate
 */
class Tinyask_Validate
{
	private $_data;
	private $_key;
	private $_rules = array();

	private $_break = false;

	public function addRule($key, $rule, $message)
	{
		if(func_num_args() <= 3) {
			$this->_rules[$key][] = array($rule, $message);
		} else {
			$params = func_get_args();
			$params = array_splice($params, 3);
			$this->_rules[$key][] = array_merge(array($rule, $message), $params);
		}

		return $this;
	}

	public function setBreak()
	{
		$this->_break = true;
	}

	public function run(array $data, $rules = null)
	{
		$result = array();
		$this->_data = $data;
		$rules = empty($rules) ? $this->_rules : $rules;

		foreach ($rules as $key => $rules) {
			$this->_key = $key;
			$data[$key] = strlen($data[$key]) == 0 ? null :$data[$key];

			foreach ($rules as $params) {
				$method = $params[0];

				if($method != 'required' && $method != 'confirm' && strlen($data[$key]) == 0) {
					continue;
				}

				$message = $params[1];
				$params[1] = $data[$key];
				$params = array_slice($params, 1);

				if(!call_user_func_array((is_array($method) ? $method : array($this, $method)), $params)) {
					$result[$key] = $message;
					break;
				}
			}

			if($this->_break && $result) {
				break;
			}
		}

		return $result;
	}

	public function confirm($string, $key)
	{
		return !empty($this->_data[$key]) ? $string == $this->_data[$key] : empty($string);
	}

	public function required($string)
	{
		return !empty($this->_data[$this->_key]);
	}

	public static function minLength($string, $length)
	{
		return (Tinyask_Common::strlen($string) >= $length);
	}

	public static function maxLength($string, $length)
	{
		return (Tinyask_Common::strlen($string) < $length);
	}

	public static function enum($string, array $params)
	{
		return in_array($string, $params);
	}

	public static function email($string)
	{
		return preg_match("/^([a-z0-9\+_\-]+)(\.[a-z0-9\+_\-]+)*@([a-z0-9\-]+\.)+[a-z]{2,6}$/ix", $string);
	}

	public static function url($string)
	{
		return preg_match("|^http://[_=&///?\.a-zA-Z0-9-]+$|i", $string);
	}

	public static function alpha($string)
	{
		return preg_match("/^([a-z])+$/i", $string) ? true : false;
	}

	public static function alphaNumeric($string)
	{
		return preg_match("/^([a-z0-9])+$/i", $string);
	}

	public static function alphaDash($string)
	{
		return preg_match("/^([_a-z0-9])+$/i", $string);
	}

	public static function isFloat($string)
	{
		return preg_match("/^[0-9\.]+$/", $string);
	}

	public static function isInteger($string)
	{
		return is_numeric($string);
	}
}
